<template>
  <div class="charge-order-create">
    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
      <h2>启动充电 - 创建订单</h2>
      <el-button type="primary" @click="goToOrderManage">查看历史订单</el-button>
    </div>

    <!-- 充电桩筛选 -->
    <el-form :inline="true" :model="queryForm" class="mb-4">
      <el-form-item label="充电桩编号">
        <el-input v-model="queryForm.pileCode" placeholder="请输入充电桩编号" />
      </el-form-item>
      <el-form-item label="安装位置">
        <el-input v-model="queryForm.location" placeholder="请输入安装位置" />
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="queryForm.status" placeholder="全部">
          <el-option label="空闲" value="0" />
          <el-option label="占用" value="1" />
          <el-option label="故障" value="2" />
          <el-option label="维护" value="3" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="fetchPileList">筛选</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 充电桩列表（选择后启动充电） -->
    <el-table :data="pileList" border style="width: 100%" @row-click="selectPile">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="pileCode" label="充电桩编号" />
      <el-table-column prop="location" label="安装位置" />
      <el-table-column prop="model" label="充电桩型号" />
      <el-table-column prop="power" label="功率（kW）" />
      <el-table-column prop="status" label="状态">
        <template #default="scope">
          <el-tag v-if="scope.row.status === 0" type="success">空闲</el-tag>
          <el-tag v-else-if="scope.row.status === 1" type="warning">占用</el-tag>
          <el-tag v-else-if="scope.row.status === 2" type="danger">故障</el-tag>
          <el-tag v-else type="info">维护</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="manufacturer" label="设备厂商" />
      <el-table-column label="操作">
        <template #default="scope">
          <el-button 
            type="primary" 
            size="small" 
            @click="startCharge(scope.row)"
            :disabled="scope.row.status !== 0"
          >
            启动充电
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination 
      @size-change="handleSizeChange" 
      @current-change="handleCurrentChange"
      :current-page="queryForm.pageNum" 
      :page-sizes="[10, 20, 50]" 
      :page-size="queryForm.pageSize" 
      :total="pileTotal"
      layout="total, sizes, prev, pager, next, jumper" 
    />

    <!-- 充电中弹窗（实时显示充电状态） -->
    <el-dialog :visible.sync="chargingDialogVisible" title="充电中" width="50%" :close-on-click-modal="false">
      <div class="charging-status">
        <div class="status-item">
          <label>订单编号：</label>
          <span>{{ currentOrder.orderNo || '生成中...' }}</span>
        </div>
        <div class="status-item">
          <label>充电桩：</label>
          <span>{{ currentOrder.pileCode }} ({{ currentOrder.pileLocation }})</span>
        </div>
        <div class="status-item">
          <label>启动时间：</label>
          <span>{{ currentOrder.startTime }}</span>
        </div>
        <div class="status-item">
          <label>当前时长：</label>
          <span>{{ formatDuration(currentOrder.duration || 0) }}</span>
        </div>
        <div class="status-item">
          <label>已用电量：</label>
          <span>{{ (currentOrder.powerUsed || 0).toFixed(2) }} kWh</span>
        </div>
        <div class="status-item">
          <label>当前电价：</label>
          <span>{{ currentOrder.unitPrice || 0 }} 元/kWh</span>
        </div>
        <div class="status-item">
          <label>预估费用：</label>
          <span class="amount">{{ (currentOrder.totalAmount || 0).toFixed(2) }} 元</span>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="pauseCharge">暂停充电</el-button>
          <el-button type="primary" @click="stopCharge">结束充电</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request'
import { formatDate } from '@/utils/dateUtils' // 需自行实现日期格式化工具

export default {
  name: 'ChargeOrderCreate',
  data() {
    return {
      // 充电桩查询参数
      queryForm: {
        pageNum: 1,
        pageSize: 10,
        pileCode: '',
        location: '',
        status: ''
      },
      pileList: [],
      pileTotal: 0,
      // 充电中订单信息
      chargingDialogVisible: false,
      currentOrder: {},
      // 充电计时定时器
      chargeTimer: null
    }
  },
  mounted() {
    this.fetchPileList()
  },
  beforeDestroy() {
    // 清除定时器
    if (this.chargeTimer) {
      clearInterval(this.chargeTimer)
    }
  },
  methods: {
    // 跳转到订单管理页
    goToOrderManage() {
      this.$router.push('/order/manage') // 需配置路由
    },
    // 获取充电桩列表（用于选择充电设备）
    async fetchPileList() {
      const loading = this.$loading({ lock: true, text: '加载充电桩...', spinner: 'el-icon-loading' })
      try {
        const response = await request({
          url: '/pile/',
          method: 'get',
          params: this.queryForm
        })
        if (response.code === 200) {
          this.pileList = response.data.records || []
          this.pileTotal = response.data.total || 0
        } else {
          this.$message.error(response.data.msg || '获取充电桩失败')
        }
      } catch (error) {
        console.error(error)
        this.$message.error(error.response?.data?.msg || '网络错误')
      } finally {
        loading.close()
      }
    },
    resetQuery() {
      this.queryForm = {
        pageNum: 1,
        pageSize: 10,
        pileCode: '',
        location: '',
        status: ''
      }
      this.fetchPileList()
    },
    handleSizeChange(val) {
      this.queryForm.pageSize = val
      this.fetchPileList()
    },
    handleCurrentChange(val) {
      this.queryForm.pageNum = val
      this.fetchPileList()
    },
    selectPile(row) {
      this.$refs.pileTable.toggleRowSelection(row) // 需给el-table加ref="pileTable"
    },
    // 启动充电（创建订单）
    async startCharge(pile) {
      if (!pile || pile.status !== 0) {
        return this.$message.warning('只能选择空闲的充电桩')
      }

      // 获取当前登录用户ID（需根据您的登录逻辑调整）
      const userId = this.$store?.state?.user?.id || localStorage.getItem('userId')
      if (!userId) {
        return this.$message.error('请先登录')
      }

      const loading = this.$loading({ lock: true, text: '启动充电中...', spinner: 'el-icon-loading' })
      try {
        // 1. 调用后端接口创建订单（充电开始）
        const response = await request({
          url: '/order/createOrder',
          method: 'post',
          data: {
            pileId: pile.id,
            pileCode: pile.pileCode,
            pileLocation: pile.location,
            userId: userId,
            startTime: formatDate(new Date(), 'yyyy-MM-dd HH:mm:ss') // 前端临时生成，以后端为准
          }
        })

        if (response.code === 200) {
          this.currentOrder = response.data
          this.chargingDialogVisible = true
          this.$message.success('充电已启动')

          // 2. 启动定时器，实时更新充电状态（模拟实时数据，实际应走WebSocket或轮询）
          this.startChargeTimer()
        } else {
          this.$message.error(response.data.msg || '启动充电失败')
        }
      } catch (error) {
        console.error(error)
        this.$message.error(error.response?.data?.msg || '启动充电失败')
      } finally {
        loading.close()
      }
    },
    // 充电计时定时器（模拟实时更新）
    startChargeTimer() {
      if (this.chargeTimer) {
        clearInterval(this.chargeTimer)
      }

      // 初始时长（秒）
      let duration = 0
      this.chargeTimer = setInterval(async () => {
        duration += 1
        this.currentOrder.duration = duration

        // 模拟用电量计算（实际应从后端获取）
        const power = this.currentOrder.power || 7.0 // 充电桩功率（kW）
        const powerUsed = (power * duration / 3600).toFixed(2) // 用电量 = 功率 * 时间（小时）
        this.currentOrder.powerUsed = Number(powerUsed)

        // 3. 调用后端接口获取实时电价（支持峰谷电价）
        try {
          const priceResponse = await request({
            url: '/order/getCurrentPrice',
            method: 'get',
            params: {
              pileId: this.currentOrder.pileId,
              time: new Date().getTime()
            }
          })
          if (priceResponse.code === 200) {
            this.currentOrder.unitPrice = priceResponse.data.unitPrice
            // 计算费用 = 用电量 * 电价
            this.currentOrder.totalAmount = (this.currentOrder.powerUsed * this.currentOrder.unitPrice).toFixed(2)
          }
        } catch (error) {
          console.error('获取电价失败', error)
        }
      }, 1000) // 每秒更新一次（实际可调整为30秒/次）
    },
    // 暂停充电（可选功能）
    async pauseCharge() {
      if (this.chargeTimer) {
        clearInterval(this.chargeTimer)
      }
      this.$message.info('充电已暂停（可点击"结束充电"结算）')
    },
    // 结束充电（更新订单状态）
    async stopCharge() {
      if (!this.currentOrder.id) {
        return this.$message.error('订单信息异常')
      }

      const loading = this.$loading({ lock: true, text: '结束充电中...', spinner: 'el-icon-loading' })
      try {
        // 清除定时器
        if (this.chargeTimer) {
          clearInterval(this.chargeTimer)
          this.chargeTimer = null
        }

        // 调用后端接口更新订单（结束充电）
        const response = await request({
          url: `/order/endCharge/${this.currentOrder.id}`,
          method: 'put',
          data: {
            endTime: formatDate(new Date(), 'yyyy-MM-dd HH:mm:ss'),
            duration: this.currentOrder.duration,
            powerUsed: this.currentOrder.powerUsed,
            totalAmount: this.currentOrder.totalAmount
          }
        })

        if (response.code === 200) {
          this.$message.success('充电已结束，可前往订单管理页支付')
          this.chargingDialogVisible = false
          this.currentOrder = {}
          // 刷新充电桩列表（更新状态为空闲）
          this.fetchPileList()
        } else {
          this.$message.error(response.data.msg || '结束充电失败')
        }
      } catch (error) {
        console.error(error)
        this.$message.error(error.response?.data?.msg || '结束充电失败')
      } finally {
        loading.close()
      }
    },
    // 格式化时长（秒转 时:分:秒）
    formatDuration(seconds) {
      const h = Math.floor(seconds / 3600).toString().padStart(2, '0')
      const m = Math.floor((seconds % 3600) / 60).toString().padStart(2, '0')
      const s = (seconds % 60).toString().padStart(2, '0')
      return `${h}:${m}:${s}`
    }
  }
}
</script>

<style scoped>
.charge-order-create {
  padding: 20px;
}

.charging-status {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  padding: 20px 0;
}

.status-item {
  width: calc(50% - 10px);
  display: flex;
  align-items: center;
  font-size: 14px;
}

.status-item label {
  width: 100px;
  color: #666;
  font-weight: 500;
}

.status-item .amount {
  color: #ff4d4f;
  font-weight: 600;
  font-size: 16px;
}
</style>